const express=require ('express')
const app=express()
const Hometab = require('./mongo/hometab')
const Homeshop =require('./mongo/homeshop')
const Userinfo =require('./mongo/userinfo')
// const express=require('express')
// const app=express()

// mongod --dbpath ../data/db
// C:\Windows\System32\cmd.exe
//E:\Program Files (x86)\MongoDB\Server\5.0\bin

//引入express-art-template
// app.engine('html',require('express-art-template'))
//配置body-parser,可以解析post来的req.body
app.use(express.urlencoded({extended:true}))
app.use(express.json())

app.all("*",function(req,res,next){
  //设置允许跨域的域名，*代表允许任意域名跨域
  res.header("Access-Control-Allow-Origin","*");
  //允许的header类型
  res.header("Access-Control-Allow-Headers","content-type");
  //跨域允许的请求方式
  res.header("Access-Control-Allow-Methods","DELETE,PUT,POST,GET,OPTIONS");
  if (req.method.toLowerCase() == 'options')
    res.sendStatus(200);  //让options尝试请求快速结束
  else
    next();
})


app.get('/gethometab',(req,res)=>{
  Hometab.find(null,null,null,(err,result)=>{
    if (err) {
      console.log(err)
    }else {
      res.send(result)
    }
  })
})

app.get('/gethomeshop',(req,res)=>{
  Homeshop.find(null,null,null,(err,result)=>{
    if (err) {
      console.log(err)
    }else {
      res.send(result)
    }
  })
})

app.post('/isRegister', (req, res) => {
 // console.log(req.body)
  //let registerInfo = new Userinfo(req.body)
  Userinfo.find(req.body, (err, result) => {
    if (err) {
      console.log(err)
    } else {
      //console.log(result.length)
      if (result.length != 0) {
        res.send('200')
        console.log("查找成功")
      }
      else{
        res.send('400')
      }
    }
  })
})

app.post('/register',(req,res)=>{
  console.log(req.body)
  let registerInfo = new Userinfo(req.body)
  registerInfo.save((err) => {
    if (err) {
      console.log(err);
      console.log('存储失败');
    }
    console.log('存储成功');
    res.send(req.body)
  })
})

app.listen(3000,()=>{
    console.log('app is running at port 3000!')
})
